package com.seh.contentcenter.component;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/chat/{userId}")
public class WebSocketHandler {

    private static final Map<Integer, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) throws IOException {
        sessions.put(userId, session);
        session.getBasicRemote().sendText("连接已建立。");
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        Integer userId = extractUserId(session);
        // 处理收到的消息
        session.getBasicRemote().sendText("你好，" + userId + "！这是一条响应消息。");
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        Integer userId = extractUserId(session);
        sessions.remove(userId);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    private Integer extractUserId(Session session) {
        String userIdStr = session.getPathParameters().get("userId");
        return Integer.parseInt(userIdStr);
    }

    private void sendMessageToUser(Integer userId, String message) throws IOException {
        Session session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }
}
